package com.xxjqr.rbac.aop;

import com.github.pagehelper.PageHelper;
import com.xxjqr.rbac.anno.PageQuery;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @描述 使用aop对做自定义分页,暂时只支持get方式
 * @码农 丁昌江
 * @日期 2021/3/9 21:40
 */
@Aspect
@Component
public class PageAop{
    @Around("@annotation(pageQuery)")
    public Object pageQuery(ProceedingJoinPoint joinPoint, PageQuery pageQuery) throws Throwable {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        //Class<?> returnType = signature.getMethod().getReturnType();
        //if (returnType == List.class) {
            String pageNumParameterName = pageQuery.pageNumParameterName();
            String pageSizeParameterName = pageQuery.pageSizeParameterName();
            //获取request，从中获取分页参数
            ServletRequestAttributes currentRequestAttributes = (ServletRequestAttributes) RequestContextHolder
                    .currentRequestAttributes();
            HttpServletRequest request = currentRequestAttributes.getRequest();
            String pageNum = request.getParameter(pageNumParameterName);
            String pageSize = request.getParameter(pageSizeParameterName);
            int pageNumInt = 0,pageSizeInt = 0;
            if (StringUtils.hasLength(pageNum) && StringUtils.hasLength(pageSize)) {
                pageNumInt = Integer.parseInt(pageNum);
                pageSizeInt = Integer.parseInt(pageSize);
            } else {
                if (!StringUtils.hasLength(pageNum)) {
                    pageNumInt = pageQuery.pageNumDefault();
                }
                if (!StringUtils.hasLength(pageSize)){
                    pageSizeInt = pageQuery.pageSizeDefault();
                }
            }
            try {
                PageHelper.startPage(pageNumInt, pageSizeInt);
                return joinPoint.proceed();
                //Object result = joinPoint.proceed();
                //return new PageInfo<>((List<?>) result);//建议自己实现返回类型，官方自带的返回数据太冗余了
            } finally {//保证线程变量被清除
                if (PageHelper.getLocalPage() != null)
                    PageHelper.clearPage();
            }
        //}
        //return joinPoint.proceed();
    }
}
